package id.co.gomobile.assessment

import org.codehaus.groovy.grails.plugins.springsecurity.Secured;

import grails.converters.JSON;

class MainController {
	
	static allowedMethods = [start: "POST", setAnswer: "POST", addAnswer: "POST", removeAnswer: "POST", resetAnswer: "POST"]
	
	def assessmentService
	
	def home = {
		if(request.getRemoteUser()) {
			def user = User.findByUsername(request.getRemoteUser())
			def assignmentInstanceList = Assignment.findAllByUser(user)
			def newAssignmentInstanceList = Assignment.findAllByUserAndEndTimeIsNull(user)
			
			[userInstance: user, assignmentInstanceList: assignmentInstanceList, newAssignmentInstanceList: newAssignmentInstanceList]
		}
	}
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
    def index = {
    	// get from session if any assignment object are sets
		def assignment = session['activeAssignment']
		if(!assignment) {
			redirect(action: "home")
		} else {
			assignment = Assignment.get(assignment.id)

			if(assessmentService.isTimeout(assignment)) {
				flash.message = "${message(code: 'default.timeout', default: 'Timeout, please submit your answers.')}"
				
				redirect(action: "submit")
			} else if(params.page == "submit") {
				redirect(action: "submit")
			} else {
				def page = params.page ? params.page.asType(int) : 0
				
				def maxPage = Math.ceil(assignment.items.size() / assignment.test.preference.maxQuestionsPerPage).asType(int)
				
				def items = assessmentService.getPage(assignment, page)
				return [assignment: assignment, items: items, maxPage: maxPage, currentPage: page+1]
			}
		}
	}
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def submit = {
		def assignment = session['activeAssignment']
		if(!assignment) {
			redirect(action: "home")
		} else {
			assignment = Assignment.get(assignment.id)

			def maxPage = Math.ceil(assignment.items.size() / assignment.test.preference.maxQuestionsPerPage).asType(int)

			return [assignment: assignment, maxPage: maxPage, currentPage: "submit"]
			//print assessmentService.getAssignmentPoint(assignment)
		}
	}
	
	// starting assessment
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def start = {
		def user = User.findByUsername(request.getRemoteUser())
		def assignmentInstance = Assignment.get(params.id)
		if (!assignmentInstance) {
			redirect(action: "home")
		} else if (assignmentInstance.user.id != user.id) {
			flash.message = "${message(code: 'default.invalid.test.session', default: 'Invalid assignment.')}"
			redirect(action: "home")
		} else {
			if(session['activeAssignment']) {
				if(assignmentInstance.id != session['activeAssignment'].id) {
					flash.message = "${message(code: 'default.active.test.session', default: 'You still have active test session. Please finish this test first.')}"
				}
				redirect(action: "index")
			} else if(assignmentInstance.endTime != null) {
				flash.message = "${message(code: 'default.finished.session', default: 'You are not allower to modify submitted assignment.')}"
				
				redirect(action: "index")
			} else {
				assessmentService.startAssignment(assignmentInstance)
				assignmentInstance.discard() // discard object
				session['activeAssignment'] = assignmentInstance
				
				redirect(action: "index")
			}
		}
	}
	
	def finish = {
		def assignmentInstance = session['activeAssignment']
		if(!assignmentInstance) { // atach
			flash.message = "${message(code: 'default.invalid.active.session', default: 'Invalid session.')}"
			redirect(uri: "/")
		} else {
			assignmentInstance = Assignment.get(assignmentInstance.id)
			
			assignmentInstance.endTime = new Date()
			assignmentInstance.total = assessmentService.getAssignmentPoint(assignmentInstance)
			if(assignmentInstance.save(flush: true)) {
				session.removeAttribute('activeAssignment');
			}

			def assigmentCategoryPoint = assessmentService.getAssignmentCategoryPoint(assignmentInstance)
			[assignmentInstance: assignmentInstance, assigmentCategoryPoint: assigmentCategoryPoint]
		}
	}
	
	// remaining time
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def remainingTime = {
		def assignmentInstance = Assignment.get(params.id)
		def remaining = assessmentService.getRemainingTime(assignmentInstance)
		
		render remaining as JSON
	}
	
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def setAnswer = {
		def assignmentItemId = params.assignmentItemId
		def itemOptionId = params.itemOptionId
		
		def assignmentItem = AssignmentItem.get(assignmentItemId)
		def itemOption = ItemOption.get(itemOptionId)

		// clear all answer
		for(answer in assignmentItem.answers) {
			//answer.delete(flush: true)
			assignmentItem.removeFromAnswers(answer)
		}
		
		assignmentItem.addToAnswers(itemOption)
	}
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def addAnswer = {
		def assignmentItemId = params.assignmentItemId
		def itemOptionId = params.itemOptionId
		
		def assignmentItem = AssignmentItem.get(assignmentItemId)
		def itemOption = ItemOption.get(itemOptionId)

		assignmentItem.addToAnswers(itemOption)
		
		// return ok / error
	}
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def removeAnswer = {
		def assignmentItemId = params.assignmentItemId
		def itemOptionId = params.itemOptionId
		
		def assignmentItem = AssignmentItem.get(assignmentItemId)
		def itemOption = ItemOption.get(itemOptionId)
		
		assignmentItem.removeFromAnswers(itemOption)
		
		// return ok / error
	}
	
	@Secured(["IS_AUTHENTICATED_FULLY"])
	def resetAnswer = {
		def assignmentItemId = params.assignmentItemId
		
		def assignmentItem = AssignmentItem.get(assignmentItemId)
		
		// clear all answer
		for(answer in assignmentItem.answers) {
			assignmentItem.removeFromAnswers(answer)
		}
		
		// return ok / error
	}

}
